from sqlalchemy import Column, Integer, String, DateTime, Text, Enum, Index
from sqlalchemy.sql import func
from app.services.db import Base
import enum

class OrderStatus(str, enum.Enum):
    pending = "pending"       # 等待被客户端拉取
    processing = "processing" # 已被客户端拉取，待确认
    executed = "executed"     # 客户端确认执行成功
    failed = "failed"         # 客户端确认执行失败
    expired = "expired"       # 超时未处理

class QuantOrder(Base):
    __tablename__ = "quant_orders"

    id = Column(Integer, primary_key=True, index=True)
    tunnel_id = Column(String(100), index=True, nullable=False)
    client_id = Column(String(100), index=True, nullable=True)

    # 原始订单数据 JSON 字符串（避免复杂类型依赖）
    data = Column(Text, nullable=False)

    # 用于去重的内容哈希（如基于 data + tunnel_id 计算）
    content_hash = Column(String(64), index=True, nullable=False)

    status = Column(Enum(OrderStatus), default=OrderStatus.pending, index=True, nullable=False)

    created_at = Column(DateTime(timezone=True), server_default=func.now(), index=True)
    processed_time = Column(DateTime(timezone=True), nullable=True)
    confirmed_time = Column(DateTime(timezone=True), nullable=True)

    # 订单时间戳（来源端提供）
    order_timestamp = Column(String(64), nullable=True)

    __table_args__ = (
        Index("ix_quant_orders_unique_hash_pending", "content_hash", "tunnel_id", unique=False),
    )